package org.aom.service.email;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.aom.model.FindPWUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * MIME邮件服务类.
 * 
 * 演示由Freemarker引擎生成的的html格式邮件, 并带有附件.
 * 
 * @author calvin
 */
public class MimeMailService {

	private static final String ENCODING = "utf-8";

	private static Logger logger = LoggerFactory
			.getLogger(MimeMailService.class);

	private JavaMailSender mailSender;
	private Template template;

	/**
	 * Spring的MailSender.
	 */
	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	/**
	 * 注入Freemarker引擎配置,构造Freemarker 邮件内容模板.
	 */
	public void setFreemarkerConfiguration(Configuration freemarkerConfiguration)
			throws IOException {
		// 根据freemarkerConfiguration的templateLoaderPath载入文件.
		template = freemarkerConfiguration.getTemplate("mailTemplate.ftl",
				ENCODING);
	}

	/**
	 * 发送MIME格式的用户修改通知邮件.
	 */
	public boolean sendNotificationMail(FindPWUser findPWUser) {
		MimeMessage msg = mailSender.createMimeMessage();

		try {
			MimeMessageHelper helper = new MimeMessageHelper(msg, true,
					ENCODING);

			helper.setTo(findPWUser.getEmail());
			helper.setFrom("zczx@admin.ustb.edu.cn");
			helper.setSubject("密码修改通知");

			buildContent(helper, findPWUser);

			mailSender.send(msg);
			logger.info("HTML版邮件已发送至valenti.y.29@gamil.com");
			System.out.println("HTML版邮件已发送至valenti.y.29@gamil.com");
			return true;
		} catch (MessagingException e) {
			logger.error("构造邮件失败", e);
			return false;
		} catch (MailException e) {
			logger.error("发送邮件失败", e);
			return false;
		}
	}

	/**
	 * 使用Freemarker生成html格式内容.
	 */
	@SuppressWarnings({ "unchecked", "deprecation" })
	private void buildContent(MimeMessageHelper helper, FindPWUser findPWUser)
			throws MessagingException {

		try {
			Map context = new HashMap();
			context.put("userName", findPWUser.getUserName());
			context.put("password", findPWUser.getPassword());
			String sendTime = (findPWUser.getCurrTime().getYear()+1900) + "年"
					+ (findPWUser.getCurrTime().getMonth()+1) + "月"
					+ (findPWUser.getCurrTime().getDay()+1) + "日";
			context.put("sendTime", sendTime);
			String content = FreeMarkerTemplateUtils.processTemplateIntoString(
					template, context);
			helper.setText(content, true);
		} catch (IOException e) {
			logger.error("构造邮件失败,FreeMarker模板不存在", e);
			throw new MessagingException("FreeMarker模板不存在", e);
		} catch (TemplateException e) {
			logger.error("构造邮件失败,FreeMarker处理失败", e);
			throw new MessagingException("FreeMarker处理失败", e);
		}
	}
}
